package com.lianyu.wangyiyun.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlendMode;
import android.graphics.BlendModeColorFilter;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.lianyu.wangyiyun.R;
import com.lianyu.wangyiyun.databinding.ActivityPlayerBinding;
import com.lianyu.wangyiyun.fragment.CoverFragment;
import com.lianyu.wangyiyun.fragment.LyricFragment;
import com.lianyu.wangyiyun.fragment.MusicDialogFragment;
import com.lianyu.wangyiyun.model.Mp3Info;
import com.lianyu.wangyiyun.model.MusicListViewModel;
import com.lianyu.wangyiyun.service.MusicService;
import com.lianyu.wangyiyun.utils.MyUtils;
import com.lianyu.wangyiyun.widget.musiceffect.view.EffectView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * @author Chen Yuguang
 */
public class PlayerActivity extends BaseActivity implements View.OnClickListener {

    private ActivityPlayerBinding activityPlayerBinding;
    private MusicService mService;
    private MusicListViewModel mainMusicListViewModel;
    private CoverFragment coverFragment;
    private final LyricFragment lyricFragment = new LyricFragment();
    /**
     * 更新播放进度的handler信号值
     */
    public static final int UPDATE_PROGRESS = 1;
    /**
     * 单线程化的定时线程池
     */
    private final ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor();
    /**
     * 单线程的任务
     */
    private ScheduledFuture<?> future;
    /**
     * 发送同步mode的广播动作值
     */
    public static final String ACTION_MUSIC_PLAYER_MODE = "com.lianyu.wangyiyun.ACTION_MUSIC_PLAYER_MODE";
    /**
     * 发送同步position的广播动作值
     */
    public static final String ACTION_MUSIC_PLAYER_POSITION = "com.lianyu.wangyiyun.ACTION_MUSIC_PLAYER_POSITION";
    /**
     * 滑动条是否被触摸
     */
    private boolean isSeekTouch = false;

    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == UPDATE_PROGRESS) {
                int position = msg.arg1;
                if (!isSeekTouch) {
                    activityPlayerBinding.progressBar.setProgress(position);
                    activityPlayerBinding.now.setText(formatTime(position));
                }
                lyricFragment.updateTime(position);
            }
        }
    };

    private class MusicProgressRunnable implements Runnable {
        @Override
        public void run() {
            if (mService != null && mService.isNotInitialized()) {
                int position = mService.getCurrentPosition();
                Message message = new Message();
                message.what = UPDATE_PROGRESS;
                message.arg1 = position;
                mHandler.sendMessage(message);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //绑定服务
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, mConn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        //解绑服务
        unbindService(mConn);
        super.onStop();
    }

    private final ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MusicService.MusicServiceBinder binder = (MusicService.MusicServiceBinder) iBinder;
            mService = binder.getService();
            //开启音频信息获取
            mService.startVisualize(new MusicService.DataCallback() {
                @Override
                public void onCall(byte[] data) {
                    if (coverFragment != null) {
                        EffectView effectView = coverFragment.getEffectView();
                        if (effectView != null) {
                            coverFragment.getEffectView().onCall(data);
                        }
                    }
                }

                @Override
                public void onWaveCall(byte[] data) {
                    if (coverFragment != null) {
                        EffectView effectView = coverFragment.getEffectView();
                        if (effectView != null) {
                            coverFragment.getEffectView().onWaveCall(data);
                        }
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mService = null;
        }
    };

    public class MusicReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case ACTION_MUSIC_PLAYER_MODE:
                    //同步mode
                    int mode = intent.getIntExtra("mode", -1);
                    if (mode != -1) {
                        mainMusicListViewModel.getModeLiveData().setValue(mode);
                    }
                    break;
                case ACTION_MUSIC_PLAYER_POSITION:
                    //同步position
                    int position = intent.getIntExtra("position", -1);
                    if (position != -1) {
                        mainMusicListViewModel.getPositionLiveData().setValue(position);
                    }
                    break;
                default:
            }
        }
    }

    @Override
    protected void onDestroy() {
        //销毁线程
        scheduled.shutdownNow();
        super.onDestroy();
    }

    @Override
    public void finish() {
        if (mService != null) {
            mService.stopVisualize();
        }
        super.finish();
        //结束动画
        overridePendingTransition(0, R.anim.bottom_out);
    }

    @Override
    protected void initData() {
        mainMusicListViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MusicListViewModel.class);
        List<Mp3Info> mp3Infos = (List<Mp3Info>) getIntent().getSerializableExtra("mp3Infos");
        if (mp3Infos != null) {
            mainMusicListViewModel.getMusicLiveData().setValue(mp3Infos);
        }
        int position = getIntent().getIntExtra("position", -1);
        if (position != -1) {
            mainMusicListViewModel.getPositionLiveData().setValue(position);
        }
        int mode = getIntent().getIntExtra("mode", -1);
        if (mode != -1) {
            mainMusicListViewModel.getModeLiveData().setValue(mode);
        }
    }

    @Override
    protected void initView() {
        activityPlayerBinding = ActivityPlayerBinding.inflate(getLayoutInflater());
        List<Fragment> mFragments = new ArrayList<>();
        boolean isPlaying = getIntent().getBooleanExtra("isPlaying", false);
        int duration = getIntent().getIntExtra("duration", -1);
        int currentPosition = getIntent().getIntExtra("currentPosition", -1);
        //初始化播放/暂停状态，总进度，当前播放时间进度
        updateSta(isPlaying);
        if (duration != -1) {
            updateDuration(duration);
        }
        if (currentPosition != -1) {
            activityPlayerBinding.progressBar.setProgress(currentPosition);
            activityPlayerBinding.now.setText(formatTime(currentPosition));
        }
        coverFragment = CoverFragment.newInstance(isPlaying);
        mFragments.add(coverFragment);
        mFragments.add(lyricFragment);
        //实例化适配器
        MyUtils.MyFragmentStateAdapter myAdapter = new MyUtils.MyFragmentStateAdapter(this, mFragments);
        //给ViewPager2设置适配器
        activityPlayerBinding.viewPager2.setAdapter(myAdapter);
        //ViewPager2设置预加载 传入大于1的值来设置预加载数量,默认不预加载
        activityPlayerBinding.viewPager2.setOffscreenPageLimit(2);
        //ViewPager2禁止滑动
        activityPlayerBinding.viewPager2.setUserInputEnabled(false);
        mainMusicListViewModel.getModeLiveData().observe(this, mode -> {
            switch (mode) {
                case MainActivity.LIST_XUN:
                    //列表循环
                    activityPlayerBinding.modeImage.setImageResource(R.drawable.listxun);
                    break;
                case MainActivity.SUI_XUN:
                    //随机循环
                    activityPlayerBinding.modeImage.setImageResource(R.drawable.suiji);
                    break;
                case MainActivity.ONE_XUN:
                    //单曲循环
                    activityPlayerBinding.modeImage.setImageResource(R.drawable.onexun);
                    break;
                default:
            }
        });
        mainMusicListViewModel.getPositionLiveData().observe(this, position -> {
            //非初始化
            if (mService != null) {
                //更新为播放状态
                updateSta(true);
                //更新总时间进度
                updateDuration(mService.getDuration());
            }
            List<Mp3Info> mp3Infos = mainMusicListViewModel.getMusicLiveData().getValue();
            if (mp3Infos != null) {
                Mp3Info mp3Info = mp3Infos.get(position);
                //设置歌名和歌手
                activityPlayerBinding.title.setText(mp3Info.getTitle());
                activityPlayerBinding.artist.setText(mp3Info.getArtist());
                String url = mp3Info.getUrl();
                String http = "http";
                if (new File(url).isFile()) {
                    Bitmap albumPicture = null;
                    //取本地专辑图
                    MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                    mediaMetadataRetriever.setDataSource(url);
                    byte[] data = mediaMetadataRetriever.getEmbeddedPicture();
                    if (data != null) {
                        //获取bitmap对象
                        albumPicture = BitmapFactory.decodeByteArray(data, 0, data.length);
                    }
                    //设置本地专辑图为背景
                    setBackground(albumPicture);
                } else if (url.startsWith(http)) {
                    String album = mp3Info.getAlbum();
                    //设置网络专辑图为背景
                    setBackground(album);
                } else {
                    //设置默认背景
                    setBackground((Bitmap) null);
                }
            }
        });
        activityPlayerBinding.progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (isSeekTouch) {
                    activityPlayerBinding.now.setText(formatTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekTouch = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekTo(seekBar.getProgress());
                isSeekTouch = false;
            }
        });
        activityPlayerBinding.down.setOnClickListener(this);
        activityPlayerBinding.modeImage.setOnClickListener(this);
        activityPlayerBinding.last.setOnClickListener(this);
        activityPlayerBinding.play.setOnClickListener(this);
        activityPlayerBinding.next.setOnClickListener(this);
        activityPlayerBinding.list.setOnClickListener(this);
        setContentView(activityPlayerBinding.getRoot());
    }

    @Override
    protected void initEvent() {
        //新建广播接收者
        MusicReceiver musicReceiver = new MusicReceiver();
        //新建广播过滤器
        IntentFilter intentFilter = new IntentFilter();
        //给过滤器添加动作
        intentFilter.addAction(ACTION_MUSIC_PLAYER_MODE);
        intentFilter.addAction(ACTION_MUSIC_PLAYER_POSITION);
        //注册广播接收者
        registerReceiver(musicReceiver, intentFilter);
    }

    /**
     * 设置背景
     *
     * @param bitmap 图片资源
     */
    private void setBackground(Bitmap bitmap) {
        if (bitmap != null) {
            Glide.with(this).load(bitmap).placeholder(new ColorDrawable(0xB2B2B2)).transform(new BlurTransformation(10, 10))
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition<? super Drawable> transition) {
                            //采用灰色遮罩，防止图片过亮
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                drawable.setColorFilter(new BlendModeColorFilter(Color.GRAY, BlendMode.MULTIPLY));
                            } else {
                                drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
                            }
                            activityPlayerBinding.background.setImageDrawable(drawable);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
        } else {
            Glide.with(this).load(R.drawable.cover).placeholder(new ColorDrawable(0xB2B2B2)).transform(new BlurTransformation(10, 10))
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition<? super Drawable> transition) {
                            //采用灰色遮罩，防止图片过亮
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                drawable.setColorFilter(new BlendModeColorFilter(Color.GRAY, BlendMode.MULTIPLY));
                            } else {
                                drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
                            }
                            activityPlayerBinding.background.setImageDrawable(drawable);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
        }
    }

    /**
     * 设置背景
     *
     * @param url 本地图片路径或网址
     */
    private void setBackground(String url) {
        if (!url.isEmpty()) {
            Glide.with(this).load(url).placeholder(new ColorDrawable(0xB2B2B2)).transform(new BlurTransformation(10, 10))
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition<? super Drawable> transition) {
                            //采用灰色遮罩，防止图片过亮
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                drawable.setColorFilter(new BlendModeColorFilter(Color.GRAY, BlendMode.MULTIPLY));
                            } else {
                                drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
                            }
                            activityPlayerBinding.background.setImageDrawable(drawable);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
        } else {
            Glide.with(this).load(R.drawable.cover).placeholder(new ColorDrawable(0xB2B2B2)).transform(new BlurTransformation(10, 10))
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition<? super Drawable> transition) {
                            //采用灰色遮罩，防止图片过亮
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                drawable.setColorFilter(new BlendModeColorFilter(Color.GRAY, BlendMode.MULTIPLY));
                            } else {
                                drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
                            }
                            activityPlayerBinding.background.setImageDrawable(drawable);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
        }
    }

    /**
     * 更新播放/暂停状态
     *
     * @param isPlaying 是否正在播放
     * @author Chen Yuguang
     * @date 2021/5/31 7:06
     */
    private void updateSta(boolean isPlaying) {
        if (isPlaying) {
            //设置播放状态
            activityPlayerBinding.play.setSelected(true);
            //开启进度监听任务
            if (future == null) {
                future = scheduled.scheduleWithFixedDelay(new MusicProgressRunnable(), 0, 100L, TimeUnit.MILLISECONDS);
            }
        } else {
            //设置暂停状态
            activityPlayerBinding.play.setSelected(false);
            //取消进度监听任务
            if (future != null) {
                future.cancel(true);
                future = null;
            }
        }
    }

    /**
     * 更新总进度
     *
     * @param duration 总进度
     * @author Chen Yuguang
     * @date 2021/5/31 20:51
     */
    private void updateDuration(int duration) {
        activityPlayerBinding.total.setText(formatTime(duration));
        activityPlayerBinding.progressBar.setMax(duration);
    }

    /**
     * 调整歌曲播放进度
     *
     * @param time 要设置的播放时间进度
     * @author Chen Yuguang
     * @date 2021/5/31 7:06
     */
    public void seekTo(int time) {
        if (mService != null) {
            mService.seekTo(time);
        }
    }

    /**
     * 是否处于播放状态
     *
     * @return boolean
     * @author Chen Yuguang
     * @date 2021/5/31 7:06
     */
    public boolean isPlaying() {
        if (mService != null) {
            return mService.isPlaying();
        } else {
            return false;
        }
    }

    /**
     * 切换viewPager2页面
     *
     * @author Chen Yuguang
     * @date 2021/5/31 7:50
     */
    public void switchPager() {
        if (activityPlayerBinding.viewPager2.getAdapter() != null) {
            int total = activityPlayerBinding.viewPager2.getAdapter().getItemCount();
            int current = activityPlayerBinding.viewPager2.getCurrentItem();
            int newCurrent = current + 1 == total ? 0 : current + 1;
            activityPlayerBinding.viewPager2.setCurrentItem(newCurrent, false);
        }
    }

    /**
     * 格式化时间
     *
     * @param length 时间长度
     * @return java.lang.String
     * @author Chen Yuguang
     * @date 2021/5/27 6:59
     */
    private String formatTime(int length) {
        Date date = new Date(length);
        //时间格式化工具
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss", Locale.getDefault());
        return sdf.format(date);
    }

    /**
     * 播放/暂停音乐
     */
    private void play() {
        if (mService != null) {
            if (mService.isPlaying()) {
                //设置暂停状态
                activityPlayerBinding.play.setSelected(false);
                mService.pause();
                //暂停旋转动画
                if (coverFragment != null) {
                    coverFragment.pauseAnimator();
                }
                //取消进度监听任务
                if (future != null) {
                    future.cancel(true);
                    future = null;
                }
            } else {
                //设置播放状态
                activityPlayerBinding.play.setSelected(true);
                mService.play();
                //继续旋转动画
                if (coverFragment != null) {
                    coverFragment.continueAnimator();
                }
                //重开进度监听任务
                if (future == null) {
                    future = scheduled.scheduleWithFixedDelay(new MusicProgressRunnable(), 0, 100L, TimeUnit.MILLISECONDS);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        //点击模式按钮
        if (v == activityPlayerBinding.modeImage) {
            sendBroadcast(new Intent(MainActivity.ACTION_MUSIC_SWITCH));
            //点击上一首按钮
        } else if (v == activityPlayerBinding.last) {
            sendBroadcast(new Intent(MainActivity.ACTION_MUSIC_LAST));
            //点击播放/暂停按钮
        } else if (v == activityPlayerBinding.play) {
            play();
            sendBroadcast(new Intent(MainActivity.ACTION_MUSIC_PLAY));
            //点击下一首按钮
        } else if (v == activityPlayerBinding.next) {
            sendBroadcast(new Intent(MainActivity.ACTION_MUSIC_NEXT));
            //点击列表按钮
        } else if (v == activityPlayerBinding.list) {
            MusicDialogFragment musicDialogFragment = new MusicDialogFragment();
            musicDialogFragment.show(getSupportFragmentManager(), "dialog");
            v.setClickable(false);
            //避免短时间内二次点击
            new Handler(Looper.myLooper()).postDelayed(() -> v.setClickable(true), 2000);
            //点击向下按钮
        } else if (v == activityPlayerBinding.down) {
            finish();
        }
    }

}